package cn.kgc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 支付宝支付的支付测试
 *
 * @author 韩宏伟
 */
@Api(description = "支付模块")
@Controller
@RequestMapping("/api")
public class AliPaymentController {

    /**
     * 支付Demo
     *
     * @param response        响应
     * @param WIDout_trade_no 订单ID 在网站本地是唯一的
     * @param WIDsubject      当前订单的名称
     * @param WIDtotal_amount 订单总价
     * @return 返回一个合成的form表单
     */
    @ApiOperation(value = "支付测试", produces = "application/json", httpMethod = "post")
    @RequestMapping(value = "/pay", produces = "text/html", method = RequestMethod.POST)
    public Object pay(HttpServletResponse response, String WIDout_trade_no, String WIDsubject, String WIDtotal_amount) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        //获取初始化的AliPayClient
        //设置超时时间
        String timeout_express = "2m";
        //销售商品码 必填
        //FAST_INSTANT_TRADE_PAY 网页端
        //QUICK_WAP_PAY手机端
        String product_code = "FAST_INSTANT_TRADE_PAY";
        //调用客户端  需要传一些参数进去 分别是 （请求的地址【这里是请求的是支付宝的测试地址】,支付宝应用ID,生成的私钥，参数格式类型，字符编码格式，应用公钥，加密类型）
        AlipayClient client = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do", AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", "UTF-8", AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        //阿里支付的当面付的请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //支付模型
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        WIDsubject = new String(WIDsubject.getBytes("UTF-8"),"UTF-8");
        model.setOutTradeNo(WIDout_trade_no);
        model.setSubject(WIDsubject);
        model.setTotalAmount(WIDtotal_amount);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        System.out.println(model);
        alipayRequest.setBizModel(model);
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        System.out.println(alipayRequest.toString());
        //form 表单生产
        String form = "";
        try {
            form = client.pageExecute(alipayRequest).getBody();
            System.out.println(form);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    @RequestMapping(value = "/return", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝GET过来反馈数据
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0 ; i < values.length ; i++){
                valueStr = ( i == values.length - 1 )? valueStr + values[i] : valueStr+ values [i] + ",";
            }
            params.put(name,valueStr);
        }
        System.out.println(params.toString());
        return "";
    }

    @RequestMapping(value = "/testPay")
    public Object testPay() {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "app_id", "your private_key", "json", "GBK", "alipay_public_key", "RSA2");
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"20150320010101001\"," +
                "\"scene\":\"bar_code\"," +
                "\"auth_code\":\"28763443825664394\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "\"subject\":\"Iphone6 16G\"," +
                "\"buyer_id\":\"2088202954065786\"," +
                "\"seller_id\":\"2088102146225135\"," +
                "\"total_amount\":88.88," +
                "\"trans_currency\":\"USD\"," +
                "\"settle_currency\":\"USD\"," +
                "\"discountable_amount\":8.88," +
                "\"body\":\"Iphone6 16G\"," +
                "      \"goods_detail\":[{" +
                "        \"goods_id\":\"apple-01\"," +
                "\"goods_name\":\"ipad\"," +
                "\"quantity\":1," +
                "\"price\":2000," +
                "\"goods_category\":\"34543238\"," +
                "\"categories_tree\":\"124868003|126232002|126252004\"," +
                "\"body\":\"特价手机\"," +
                "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
                "        }]," +
                "\"operator_id\":\"yx_001\"," +
                "\"store_id\":\"NJ_001\"," +
                "\"terminal_id\":\"NJ_T_001\"," +
                "\"extend_params\":{" +
                "\"sys_service_provider_id\":\"2088511833207846\"," +
                "\"industry_reflux_info\":\"{\\\\\\\"scene_code\\\\\\\":\\\\\\\"metro_tradeorder\\\\\\\",\\\\\\\"channel\\\\\\\":\\\\\\\"xxxx\\\\\\\",\\\\\\\"scene_data\\\\\\\":{\\\\\\\"asset_name\\\\\\\":\\\\\\\"ALIPAY\\\\\\\"}}\"," +
                "\"card_type\":\"S0JP0000\"" +
                "    }," +
                "\"timeout_express\":\"90m\"," +
                "\"auth_confirm_mode\":\"COMPLETE：转交易支付完成结束预授权;NOT_COMPLETE：转交易支付完成不结束预授权\"," +
                "\"terminal_params\":\"{\\\"key\\\":\\\"value\\\"}\"," +
                "\"promo_params\":{" +
                "\"actual_order_time\":\"2018-09-25 22:47:33\"" +
                "    }" +
                "  }");
        AlipayTradePayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response;
    }

}
